package cn.tjie.pet.service.impl;

import cn.tjie.basic.exception.BusinessException;
import cn.tjie.basic.service.IBaiduAiAuditService;
import cn.tjie.basic.util.*;
import cn.tjie.order.domain.OrderPetAcquisition;
import cn.tjie.order.mapper.OrderPetAcquisitionMapper;
import cn.tjie.org.domain.Employee;
import cn.tjie.org.domain.Shop;
import cn.tjie.org.mapper.EmployeeMapper;
import cn.tjie.org.mapper.ShopMapper;
import cn.tjie.pet.domain.SearchMasterMsg;
import cn.tjie.pet.domain.SearchMasterMsgAuditLog;
import cn.tjie.pet.dto.MsgDto;
import cn.tjie.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.tjie.pet.mapper.SearchMasterMsgMapper;
import cn.tjie.pet.query.SearchMasterMsgQuery;
import cn.tjie.pet.service.ISearchMasterMsgService;
import cn.tjie.basic.service.impl.BaseServiceImpl;
import cn.tjie.user.domain.Logininfo;
import cn.tjie.user.domain.User;
import cn.tjie.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {

        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //2.根据logininfo的id查询user用户的数据
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //3。获取user的id设置进msg里面的userId寻主发布用户
        msg.setUserId(user.getId());
        //4，将寻主消息添加到数据库
        searchMasterMsgMapper.save(msg);

        //5.百度AI智能审核
        //5.1.审核文本
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        //5.2 审核图片
        Boolean boo2 = baiduAiAuditService.textAudit(msg.getResources());
        //6.1.审核成功
        if(boo1&&boo2){
            //1.a.修改状态：0 - 1
            msg.setState(1);//1代表审核通过
            //添加审核日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            //修改审核日志状态
            searchMasterMsgAuditLog.setState(1);
            searchMasterMsgAuditLog.setMsgId(msg.getId());
            searchMasterMsgAuditLog.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);

            //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            //判断这个有没有小于50公里的店铺
            if(nearestShop!=null){
                //找到了最近店铺,修改msg里面的店铺id
                msg.setShopId(nearestShop.getId());
                //发消息给店铺管理员去接宠物
                //SmsUtils.sendSms(nearestShop.getTel(),"去"+msg.getAddress()+"接宠物");
                System.out.println("去"+msg.getAddress()+"接宠物");

            }else {
                //50公里内没有找到店铺
                msg.setState(3);//掉入公共池
                //发消息给寻主发布人
                //SmsUtils.sendSms(user.getPhone(),"11111");
                System.out.println("对不起，你位置太偏了");
            }
            //把状态更新
            searchMasterMsgMapper.update(msg);
            //返回给前端
            return new AjaxResult();

        }else {
            //审核不通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);

            //删除寻主消息
            searchMasterMsgAuditLogMapper.del(msg.getId());
            //b.给用户发短信或邮件：告诉它发布失败，请重新修改信息重新发布
            //SmsUtils.sendSms(user.getPhone(),"发布失败，请重新修改信息重新发布");
            //System.out.println("发布失败，请重新修改信息重新发布");
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息发布失败");
        }
    }

    /**
     * 管理员查看完成的业务--分平台和非平台
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()==null){
            //是店铺管理员
            query.setShopId(employee.getShop_id());//只查询自己店铺的
        }
        return super.pageQuery(query);
    }

    /**
     * 管理员查看公共池的业务
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.pageQuery(query);
    }

    /**
     * 管理员查看待处理的业务--分平台和非平台
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()==null){
            //是店铺管理员
            query.setShopId(employee.getShop_id());//只查询自己店铺的
        }
        return super.pageQuery(query);
    }

    /**
     * 用户查看自己的订单
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    /**
     * 拒单的业务
     * @param id
     */
    @Override
    public void reject(Long id) {
        //拒接单，把状态改成3，掉入公共池，把shop_id变为空，去mapper.xml里面写死
        searchMasterMsgMapper.reject(id);
    }

    @Override
    @Transactional
    public void accept(MsgDto msgDto) {
        //平台将寻主消息分给你这个店铺
        //店铺接收了，并且指派一个人去接宠物
        //判断订单是否存在 - 存在就说明有人已经去接单了--不应该重复接单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());
        if (order!=null&&order.getState()==0){
            throw new BusinessException("单子正有人在执行");
        }

        //1.生成收购订单
        //1.1 根据msgid 找到寻主发布消息
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition newOrder =createOrder(msg,msgDto);
        //2.告诉处理人在规定时间内接回宠物 - 发短信-2天
        //Employee employee = employeeMapper.loadById(newOrder.getEmpId());
        //SmsUtils.sendSms(employee.getPhone(),"请2天内到"+msg.getAddress()+"去接回宠物");
        orderPetAcquisitionMapper.save(newOrder);
        System.out.println("请2天内到"+msg.getAddress()+"去接回宠物");

    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //根据工具类生成订单号
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);//设置订单号
        order.setDigest(msgDto.getNote());
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //order.setState();
        //order.setPaytype(0);
        //order.setPetId();
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
